package com.openatc.agent.service.impl;

import com.openatc.agent.service.FeatureRequest;
import com.openatc.agent.service.FeatureService;
import com.openatc.agent.service.GenericMsgStrategy;
import com.openatc.agent.utils.RedisTemplateUtil;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.openatc.core.common.IErrorEnumImplInner.E_110;

/**
 * @Classname GetPhase
 * @Description
 * @Date 2022/7/19 16:40
 * @Created by panleilei
 */
@Service(value = "feature/phase")
public class FeaturePhaseRequest extends FeatureRequest {
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    private String keyType = "response:feature/phase:";

    @Autowired
    private FeatureService featureService;

    @Autowired
    private CommServiceDown commServiceDown;

    /**
     * 成功上载相位参数
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successGetProcess(MessageData requestData, RESTRet responseData) {
        MessageData messageData = (MessageData) responseData.getData();
        updatePhaseCache(requestData.getAgentid(),messageData);
        //  更新dev表中的相位数量字段
//        int row = updateDevPhaseCount(messageData);
//        if (row == 0) {
//            logger.warning("update phase count failed!");
//        }
        return super.successGetProcess(requestData, responseData);
    }

    /**
     * 成功上/下载相位参数后，更新dev表中的相位数量
     * @param messageData
     * @return
     */
    private int updateDevPhaseCount(MessageData messageData) {
        String dataSourceFieldName = "phaseList";
        return commServiceDown.updateDevFeatureCount(dataSourceFieldName,FieldName.PHASE_COUNT,messageData);
    }

    /**
     * 成功下载相位参数
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successSetProcess(MessageData requestData, RESTRet responseData) {
        String agentid = requestData.getAgentid();
        RESTRet restRet = featureService.deleteFeatureByAgentid(agentid);
        if (!restRet.isSuccess()) {
            logger.warning("MsgPostHandler process: clear feature failed!");
        }
        // 更新相位参数的缓存
        updatePhaseCache(agentid,requestData);
        //  更新dev表中的相位数量字段
        int row = updateDevPhaseCount(requestData);
        if (row == 0) {
            logger.warning("update phase count failed!");
        }
        return super.successSetProcess(requestData, responseData);
    }

    /**
     * 向信号机请求相位参数应答失败
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet failureGetProcess(MessageData requestData, RESTRet responseData) {
        InnerError innerError = (InnerError) responseData.getData();
        // 上次请求未结束/信号机应答超时，从缓存中获取数据
        if (innerError.getErrorCode().equals(E_110.getErrorCode()) ) {
            return redisTemplateUtil.getCacheData(requestData);
        }

        return super.failureGetProcess(requestData, responseData);
    }

    /**
     * 更新相位缓存数据
     * @param agentid
     * @param data
     */
    private void updatePhaseCache(String agentid, MessageData data) {
        String key = keyType + agentid;
        MessageData deepCopy = gson.fromJson(gson.toJsonTree(data), MessageData.class);
        deepCopy.setOperation("get-response");
//        data.setInfotype("feature/phase");
        deepCopy.setCreatetime(DateUtil.date2str(new Date()));
        redisTemplateUtil.setValue(key,gson.toJson(deepCopy));
    }

}
